import { Schema, model } from 'mongoose';
import { ICard, ICardModel } from '@/types/model';

const cardSchema = new Schema<ICard, ICardModel>({
    cardId: { type: String, required: true, unique: true },
    title: { type: String, required: true },
    content: { type: String, default: '' },
    listId: { type: String, required: true },
    order: { type: Number, required: true },
    createdAt: { type: Number, default: Date.now },
    updatedAt: { type: Number, default: Date.now },
    version: { type: Number, default: 0 }
}, {
    id: false,
    collection: 'cards',
    toJSON: { 
        getters: true, 
        virtuals: false,
        transform: (doc, ret) => {
            delete ret._id;
            delete ret.__v;
            return ret;
        }
    },
    toObject: { 
        getters: true, 
        virtuals: false,
        transform: (doc, ret) => {
            delete ret._id;
            delete ret.__v;
            return ret;
        }
    }
});

// 创建索引以优化查询性能
cardSchema.index({ listId: 1, order: 1 });
cardSchema.index({ cardId: 1 }, { unique: true });

// 向后移动时更新order
cardSchema.statics.updateOrderForBackwardMove = async function(listId: string, oldOrder: number, newOrder: number): Promise<unknown> {
    return this.updateMany(
        { 
            listId,
            order: { $gt: oldOrder, $lte: newOrder }
        },
        { $inc: { order: -1 } }
    );
};

// 向前移动时更新order
cardSchema.statics.updateOrderForForwardMove = async function(listId: string, oldOrder: number, newOrder: number): Promise<unknown> {
    return this.updateMany(
        {
            listId,
            order: { $gte: newOrder, $lt: oldOrder }
        },
        { $inc: { order: 1 } }
    );
};

// 获取最大order值并生成新的order
cardSchema.statics.generateNextOrder = async function(listId: string): Promise<number> {
    const maxOrderCard = await this.findOne({ listId }).sort({ order: -1 });
    return maxOrderCard ? maxOrderCard.order + 1 : 0;
};

export default model<ICard, ICardModel>('Card', cardSchema);